<?php

/**
 * 权限控制器
 * @author yanghao <yh38615890@sina.cn>
 * @date 07-04-12
 * @copyright (c) gandianli
 */

namespace app\api\controller;

use app\api\Base;
use think\Config;
use think\Db;
use think\Loader;
use think\exception\HttpException;
use com\gdl\newagk\interfaces\AuthorityServiceClient;
use com\gdl\newagk\dataobject\authority\AuthorityRequestDTO; 

class Authority extends Base
{

	//获得用户权限
    public function obtain() {
		
		$userid = $this->request->param('userid') ? (int)$this->request->param('userid') :  0;
		$plaform_id = $this->request->param('plaform_id') ? (int)$this->request->param('plaform_id') :  0; 
		if(!$userid || !$plaform_id){
			$data = ['msg'=>'缺少参数','code'=>'500','data'=>['qrcode'=>'','base'=>'']];
			return json_encode($data);
		}
        try {
			\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
            $api = new AuthorityServiceClient(NULL);
            \ApiClient::build($api);
            $engprojectDo = new AuthorityRequestDTO();
            $engprojectDo->filename['userid'] = $userid;
			$engprojectDo->filename['plaform_id'] = $plaform_id;
            $result = $api->rightsGroups($engprojectDo);

			$data = ['msg'=>'获取成功','code'=>'200','data'=>$result->data];
        } catch (Exception $ex) {
            $data = ['msg'=>'获取失败','code'=>'400','data'=>[]];
        }
        return json_encode($data);
		
    }
	
	/**
     * 获取授权列表
     * @return mixed
	 * @role_id int
     */
    public function accessList()
    {
			$role_id = $this->request->param('role_id/d');
			$username = $this->request->param('username');

			$userid = $this->request->param('userid/d');
            if (!$role_id || !$username || !$userid) {
				$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
				return json_encode($data);
            }
			try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new AuthorityServiceClient(NULL);
				\ApiClient::build($api);
				$engprojectDo = new AuthorityRequestDTO();
				$engprojectDo->id = $role_id;
				$engprojectDo->username	= $username;
				$engprojectDo->filename['userid']	= $userid;
				$result = $api->accessList($engprojectDo);
				$results = list_to_tree($result->data, "id", "pid", "ChildNodes");
				//checkstate 1是选中 0是未选中
				$data =  ['msg'=>'获取成功','code'=>'200','data'=>$results];
			} catch (Exception $ex) {
				$data = ['msg'=>'获取失败','code'=>'400','data'=>[]];
			}
			return json_encode($data);
    }
	
	
	/**
     * 组授权
     * @return mixed
	 * @id int
     */
    public function authorized()
    {
		
			$role_id = $this->request->param('role_id/d');
			$datas = $this->request->post();
            if (!$this->request->isPost() || !$role_id || empty($datas["node"])) {
				$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
				return json_encode($data);
            }
			try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new AuthorityServiceClient(NULL);
				\ApiClient::build($api);
				
				$engprojectDo = new AuthorityRequestDTO();
				$engprojectDo->filename = $datas["node"]; //这个记得处理 只能是一维数组
				$engprojectDo->filename['role_id']	= $role_id;
				$result = $api->authorized($engprojectDo);
		
				//checkstate 1是选中 0是未选中
				if($results->code){
					$data =  ['msg'=>'获取成功','code'=>'200','data'=>$results];
				} else {
					$data = ['msg'=>'获取失败','code'=>'400','data'=>[]];
				}
			} catch (Exception $ex) {
				$data = ['msg'=>'获取失败','code'=>'400','data'=>[]];
			}
			return json_encode($data);
    }
	
	/**
     * 个人授权
     * @return mixed
	 * @id int
     */
    public function userauthorized()
    {
			$plaform_id = $this->request->param('plaform_id/d');
			$userid = $this->request->param('userid/d');
			$role_id = $this->request->param('role_id/d');
            if (!$plaform_id || !$userid || !$role_id) {
				$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
				return json_encode($data);
            }
			try {
				\ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlAgkSdk'));
				$api = new AuthorityServiceClient(NULL);
				\ApiClient::build($api);
				
				$engprojectDo = new AuthorityRequestDTO();
				$engprojectDo->filename = $this->request->post()['node'];
				$engprojectDo->filename['plaform_id'] = $plaform_id;
				$engprojectDo->filename['userid']	= $userid;
				$engprojectDo->filename['role_id']	= $role_id;
				$result = $api->userAuthorized($engprojectDo);
	
				//checkstate 1是选中 0是未选中
				$data =  ['msg'=>'获取成功','code'=>'200','data'=>[]];
			} catch (Exception $ex) {
				$data = ['msg'=>'获取失败','code'=>'400','data'=>[]];
			}
			return json_encode($data);
    }
	
	/**
     * 权限组列表 这个不需要接口
     * @return mixed
	 * @id int
     */
    public function rightsGroups()
    {
		$plaform_id = $this->request->param('plaform_id/d');
		$page = $this->request->param('p')>1 ? $this->request->param('p/d') : 1;
		$pagesize = $this->request->param('num')>0 ? $this->request->param('num/d') : 10;
         if (!$plaform_id) {
			$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
			return json_encode($data);
        }
		$p = ($page-1)*$pagesize;
		$adminRole = new \app\common\model\AdminRole();
		//$child_plaform = getChildAdminRegByPlaformId($plaform_id,0);
		$child_plaform = [1];

		$cond = 'isdelete=0';
		if(!empty($child_plaform)){
			$cond .= " and admin_reg in('".implode("','",$child_plaform)."')";
		}
		
		if($this->request->param('status')>-1){

			$cond .= ' and status='.$this->request->param('status');
		}
		
		if($this->request->param('title')){
			$cond .= " and (name like '%{$this->request->param('title')}%' or remark like '%{$this->request->param('title')}%' )";
			
		}
		$list = $adminRole->field('id,pid,name')->where($cond)->limit($p.','.$pagesize)->select();
		$autList = [];
		foreach($list as $v){
			$autList[] = ['id'=>$v->id,'pid'=>$v->pid,'name'=>$v->name];
		}
		$num = $adminRole->field('count(*) num')->where($cond)->find();
		$data = ['msg'=>'获取成功','code'=>'200','data'=>$autList,'num'=>$num['num']];
		return json_encode($data);
	}
	/**
     * 添加权限组
     * @return mixed
	 * @id int
     */
    public function groupsAdd()
    {
		$plaform_id = $this->request->param('plaform_id/d');
		$name = $this->request->param('name');
		$pid = $this->request->param('pid/d');
		$userid = $this->request->param('userid/d');
		$remark = $this->request->param('remark');
		$admin_reg = $this->request->param('reg');
         if ($name=='' || !$plaform_id) {
			$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
			return json_encode($data);
        }
		$adminRole = new \app\common\model\AdminRole();
		$data = [
				'pid'=>$pid,
				'name'=>$name,
				'remark'=>$remark,
				'plaform_id'=>$plaform_id,
				'create_time'=>time(),
				'update_time'=>time(),
				'admin_reg'=>$admin_reg,
				];
		$adminRole->insert($data);
		$data = ['msg'=>'添加成功','code'=>'200','data'=>[]];
		return json_encode($data);
	}
	/**
     * 修改权限组名字
     * @return mixed
	 * @id int
     */
    public function groupsEdit()
    {

		$id = $this->request->param('id/d');
		$name = $this->request->param('name');
		$remark = $this->request->param('remark');
		$admin_reg = $this->request->param('reg');
         if (!$id) {
			$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
			return json_encode($data);
        }
		$adminRole = new \app\common\model\AdminRole();
		$data = [];
		if(!empty($name)) $data['name'] = $name;
		if(!empty($remark)) $data['remark'] = $remark;
		if(!empty($data)){
			$ret = $adminRole->where(['id'=>$id,'admin_reg'=>$admin_reg])->update($data);
		}
		$data = ['msg'=>'修改成功','code'=>'200','data'=>[]];
		return json_encode($data);
	}
	
	/**
     * 删除权限组
     * @return mixed
	 * @id int
     */
    public function groupsDede()
    {
		$admin_reg = $this->request->param('reg');
		$id = $this->request->param('id/d');
		$isTrue = $this->request->param('istrue') ? $this->request->param('istrue') : 0;
         if (!$id) {
			$data = ['msg'=>'缺少必要参数','code'=>'500','data'=>[]];
			return json_encode($data);
        }
		$adminRole = new \app\common\model\AdminRole();
		if($isTrue){
			$ret = $adminRole->where(['id'=>$id,'admin_reg'=>$admin_reg])->delete();
			if($ret){
				$AdminAccess = new \app\common\model\AdminAccess();
				$ret = $AdminAccess->where(['role_id'=>$id])->delete();
			}
		} else {
			$ret = $adminRole->where(['id'=>$id,'admin_reg'=>$admin_reg])->update(['isdelete'=>'1']);
		}
		$data = ['msg'=>'删除成功','code'=>'200','data'=>$autList];
		return json_encode($data);
	}
	
	/**
     * 往权限组添加人
     * @return mixed
	 * @datas array
     */
    public function groupsUserAdd()
    {
		$role_id = $this->request->param('id/d');
		$plaform_id = $this->request->param('plaform_id/d');
            // 提交
            if (!$role_id || !$plaform_id) {
				$data = ['msg'=>'缺少必要参数','code'=>'200','data'=>$autList];
				return json_encode($data);
            }

            $db_role_user = new \app\common\model\AdminRoleUser;
			$role_access = new \app\common\model\AdminAccess;
            $data = $this->request->post();
		
			/****新的删除方法***/
			if(!empty($userid)){
					$db_role_user->where(['role_id'=>$role_id,"user_id"=>['in',$data['user_id']]])->delete();
			}
				/****新的删除方法 end***/
            if (isset($data['user_id']) && !empty($data['user_id']) && is_array($data['user_id'])) {
				
                $insert_all = [];
                foreach ($data['user_id'] as $v) {
                    $insert_all[] = [
                        "role_id" => $role_id,
                        "user_id" => intval($v),
                    ];
                }
                $db_role_user->insertAll($insert_all);
            }
			$groups = $role_access->where(array('role_id' => $role_id),'node_id,level,pid')->select();
			if(!empty($groups)){
				foreach($groups as $vc){
					 $insert_allc[] = [
							"plaform_id" => $plaform_id,
							"userid" => $userid,
							"node_id" => $vc['node_id'],
							"level"   => $vc['level'],
							"pid"     => $vc['pid'],
						];
				}
				$db_role_user->insertAll($insert_allc);
			}
			$data = ['msg'=>'分配角色成功','code'=>'200','data'=>$autList];
			return json_encode($data);
        
	}
	
	/**
     * 去掉权限组中的人
     * @return mixed
	 * @datas array
     */
    public function groupsUserDe()
    {
		$role_id = $this->request->param('id/d');
		$bid = $this->request->param('bid') ? 1 : 0;
		$userid = $this->request->param('userid') ? $this->request->param('userid') : [];
            // 提交
            if (!$role_id || (empty($userid) && !$bid)) {
				$data = ['msg'=>'缺少必要参数','code'=>'200','data'=>$autList];
				return json_encode($data);
            }

            $db_role_user = new \app\common\model\AdminRoleUser;

            $data = $this->request->post();
		
			/****新的删除方法***/
			if(!empty($userid) && !$bid){
					$db_role_user->where(['role_id'=>$role_id,"user_id"=>['in',$userid]])->delete();
			}
			if(empty($userid) && $bid){
				$db_role_user->where(['role_id'=>$role_id])->delete();
			}
			
			$data = ['msg'=>'删除角色成功','code'=>'200','data'=>$autList];
			return json_encode($data);
        
	}
	

}
